<template>
  <div>
    <div class="main-head flex-between container-fluid">
      <div class="title">
        <h1 v-text="$t('pro.admin.StyleSettings')"></h1>
      </div>
    </div>
    <div class="content container-fluid">
      <a-spin :spinning="spinning">
        <div class="portlet">
          <div class="style-form grid">
            <a-form layout="vertical" :form="form" @submit="handleSubmit">
                <a-form-item :label="$t('pro.admin.Style')">
                  <a-radio-group
                          @change="bgColorChange"
                          v-decorator="['style.setStyle',{ initialValue: style }]"
                  >
                    <a-radio value="white">{{$t('pro.admin.White')}}</a-radio>
                    <a-radio value="dark">{{$t('pro.admin.Dark')}}</a-radio>
                  </a-radio-group>
                </a-form-item>

                <a-form-item :label="$t('pro.admin.CompanyNameText')">
                  <a-input maxlength="50" v-decorator="['style.companyName',{ initialValue: companyInfo.companyName }]"/>
                </a-form-item>

                <a-form-item :label="$t('pro.admin.CompanyTypeText')">
                  <a-input maxlength="25" v-decorator="['style.companyType',{ initialValue: companyInfo.companyType }]"/>
                </a-form-item>

                <!-- 页头文本 -->
                <a-form-item :label="$t('pro.admin.SubtitleText')">
                    <a-input maxlength="50" v-decorator="['style.subTitle',{ initialValue: companyInfo.subTitle }]"/>
                </a-form-item>

                <!-- 页脚文本 -->
                <a-form-item :label="$t('pro.admin.FooterText')">
                  <a-input maxlength="150" v-decorator="['style.footerText',{ initialValue: companyInfo.footerText }]"/>
                </a-form-item>


                <!-- 图片 -->
                <a-form-item :label="$t('pro.admin.Headerlogo')">
                    <div class="clearfix" v-if="bgImageFile.flay">
                        <img-clip
                                rate="29:10"
                                @getImg="getFile($event, 'bgImageFile')"
                        >
                        </img-clip>
                    </div>
                    <div v-else class="back-img-clip" style="width: 220px;">
                        <div class="img-clip-songs" @click="clipImgRemove('bgImageFile')">
                            <img :src="bgImageFile.img" width="100%">
                            <a-icon class="clip-img-remove" type="delete" />
                            <div class="clip-img-model"></div>
                        </div>
                    </div>
                </a-form-item>

                <a-form-item :label="$t('pro.admin.LoginLogo')">
                    <div class="clearfix" v-if="logoFile.flay">
                        <img-clip
                            rate="29:10"
                            @getImg="getFile($event, 'logoFile')"
                        >
                        </img-clip>
                    </div>
                    <div v-else class="back-img-clip" style="width: 220px;">
                        <div class="img-clip-songs" @click="clipImgRemove('logoFile')">
                            <img :src="logoFile.img" width="100%">
                               <a-icon class="clip-img-remove" type="delete" />
                            <div class="clip-img-model"></div>
                        </div>
                    </div>
                </a-form-item>


                <a-form-item :label="$t('pro.admin.Faviconupload')">
                    <div v-if="faviconFile.flay" class="clearfix">
                        <img-clip
                           @getImg="getFile($event, 'faviconFile')"
                        >
                        </img-clip>
                    </div>
                    <div v-else class="back-img-clip">
                        <div class="img-clip-songs" @click="clipImgRemove('faviconFile')">
                            <img :src="faviconFile.img" width="100%">
                            <a-icon class="clip-img-remove" type="delete" />
                            <div class="clip-img-model"></div>
                        </div>
                    </div>
                </a-form-item>


                <a-form-item>
                  <a-button type="primary" html-type="submit" v-text="$t('pro.admin.Savechanges')"></a-button>
                </a-form-item>
              </a-form>
          </div>
      </div>
      </a-spin>
    </div>


  </div>
</template>

<script>
import { updateTheme } from "@/assets/JSfunction";
import { getCompanyStyle } from "@/api/company-style";
import { mapActions } from "vuex";

import ImgClip from '../../components/common/custom/ImgClip'
import ImgCutter from 'vue-img-cutter'

export default {
 components: {  ImgClip, ImgCutter },
  data() {
    return {
      form: this.$form.createForm(this),
      style: this.$root.$children[0].ownStyle || 'white',
      src: "",
      bgImage: [],
      logo: [],
      favicon: [],
      id: "",
      spinning: false,

        bgImageFile: {
            img: "",
            flay: true,
            file: null
        },
        logoFile: {
            img: "",
            flay: true,
            file: null
        },
        faviconFile: {
            img: "",
            flay: true,
            file: null
        },

    };
  },
  methods: {
    ...mapActions(["SetCompanyStyle"]),

    bgColorChange(e) {
        //监听watch style值 发生就改变
      this.style = e.target.value;
      //打包时候会出现报错
      /*updateTheme(this.style);*/
    },

    //链接转图片
    urltoImage (url,fn){
        var img = new Image();
        img.src = url;
        img.onload = function(){
          fn(img);
        }
    },

    //保存提交
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        
        if (!err && !this.bgImageFile.flay && !this.faviconFile.flay && !this.logoFile.flay) {
          let formData = new FormData();

          formData.append("id", this.id);

          for (let item in values.style) {
              formData.append(item, values.style[item]);
          }

          if (this.logoFile.file) {
             formData.append("logo", this.logoFile.file);
          }

          if (this.bgImageFile.file) {
            formData.append("bgImage", this.bgImageFile.file);
          }

          if (this.faviconFile.file) {
            formData.append("favicon", this.faviconFile.file);
          }

          const { SetCompanyStyle } = this;

          this.spinning = true;
          SetCompanyStyle(formData)
            .then(res => {
               if(res.code == '200'){
                   //成功调用查询替换icon和网站title
                   this.$store.dispatch('GetCompanyStyle').then(resDate => {
                       let res = resDate.data || {};
                       document.querySelector('link[rel="icon"]').setAttribute('href', res.favicon || "");
                       document.title = `${res.companyName}`
                   });
                   this.$message.success(this.$t('pro.Editcampaigns.operationSuccess'));
               }
            }).catch(err => {
              console.log(err);
          }).finally(() => { this.spinning = false; })
        }else {
          //
          this.$message.warning(this.$t('pro.EditCreatives.ImageURLMess'))
        }
      });
    },

    getFile(file, key) {
        if (file) {
           this.$nextTick(() => {
               this[key].flay = false;
               this[key].img = file.dataURL;
               this[key].file = file.file;

           })

        }
    },
    clipImgRemove(aget) {
        this[aget].flay = true;
        this[aget].img = '';
    },
  },
  watch: {
      style(newVal) {
          this.$store.dispatch("setStyleColor", newVal)
      }
  },
  computed: {
    companyInfo() {
      return this.$store.getters.companyInfo;
    }
  },
  mounted() {
    getCompanyStyle()
      .then(res => {
          const obj = res.data.data;
          this.form = this.$form.createForm(this, {
          // 当Form.Item子节点的值发生改变时触发，可以把对应的值转存到 Redux store
          onFieldsChange: (_, changedFields) => {},
          // 把 props 转为对应的值，可用于把 Redux store 中的值读出,可以在此给form赋值
          mapPropsToFields: () => {
              let data = {};
              data.style = {};
              if (!obj) return data;
              for (let [key, value] of Object.entries(obj)) {
                  if (value == null) continue;
                  data.style[key] = this.$form.createFormField({ value });

                  if (key === "logo" || key === "bgImage" || key === "favicon") {
                      this[key+'File'] = {
                          img: value,
                          flay: false
                      };
                  }
              }
              
              

              return data;
          },
          // 任一表单域的值发生改变时的回调
          onValuesChange: (_, values) => {}
          });

          this.style = obj.setStyle || "white";
          this['id'] = obj.id || "";
      })
  },
};
</script>


<style lang="less" scoped>
.style-form {
  grid-template-columns: repeat(3, 1fr);
}
.back-img-clip {
    width: 110px;height: 110px;border: 1px solid #e6d8d8;border-radius: 5px;padding: 6px;
    .img-clip-songs {
        width: 100%;height: 100%;
        overflow: hidden;
        position: relative;
        .clip-img-remove {
            position: absolute;
            top: 50%;
            left: 50%;
            font-size: 1.8rem;
            color: #fff;
            z-index: 10;
            opacity: 0;
        }
        .clip-img-model {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left:0;
        }
    }
    .img-clip-songs:hover {
        z-index: 999;
        .clip-img-remove {
            cursor: pointer;
            transform: translate(-50%, -50%);
            opacity: 1;
            transition: all 0.3s;
        }
        .clip-img-model {
            background:rgba(0,0,0,0.55);
            transition: all 0.3s;
        }
    }
}
@media screen and(max-width: 992px) {
  .style-form {
    grid-template-columns: repeat(2, 1fr);
  }
}
@media screen and(max-width: 768px) {
  .style-form {
    grid-template-columns: 1fr;
  }
}
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
div.clearfix .hidden {
  // visibility: hidden;
  cursor: not-allowed;
}
</style>
